package com.base.vistter.iframe.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.base.vistter.iframe.bean.SystemContextHolder;
import com.base.vistter.iframe.model.LoginUserModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class SaveOrUpdateHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ...");
        Date date = new Date();
        LoginUserModel loginUserModel = SystemContextHolder.getSessionContext();
        this.strictInsertFill(metaObject, "creator", Integer.class, loginUserModel != null ? loginUserModel.getUserId() : null);
        this.strictInsertFill(metaObject, "createDate", Date.class, date);
        this.strictInsertFill(metaObject, "modifier", Integer.class, loginUserModel != null ? loginUserModel.getUserId() : null);
        this.strictInsertFill(metaObject, "modifyDate", Date.class, date);
        this.strictInsertFill(metaObject, "isDelete", Integer.class, 0);
        //如果用户，部门由前端设置。
        if(getFieldValByName("sysDepartId", metaObject) == null){
            this.strictInsertFill(metaObject, "sysDepartId", Integer.class, loginUserModel != null ? loginUserModel.getDepartId() : null);
        }
        this.strictInsertFill(metaObject, "sysFirmId", Integer.class, loginUserModel != null ? loginUserModel.getFirmId() : null);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        LoginUserModel loginUserModel = SystemContextHolder.getSessionContext();
        this.strictUpdateFill(metaObject, "modifyDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "modifier", Integer.class, loginUserModel != null ? loginUserModel.getUserId() : null);
    }
}
